package com.citcc.api.utils;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipaySystemOauthTokenRequest;
import com.alipay.api.request.AlipayUserInfoShareRequest;
import com.alipay.api.response.AlipaySystemOauthTokenResponse;
import com.alipay.api.response.AlipayUserInfoShareResponse;
import com.citcc.business.bean.dto.BindAlipayUserInfo;
import com.citcc.business.bean.vo.PersonalCenterAlipayLoginParamVO;
import com.citcc.business.util.IdGenerator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.net.URLEncoder;
import java.util.SortedMap;
import java.util.TreeMap;

/**
 * Created by czh on 2019/5/22 0022 19:50
 */
@Component
public class BindAlipayServiceUtil {

    @Value("${pay.zhifubao.apppay.privateKey}")
    private String privateKey;
    @Value("${pay.zhifubao.apppay.publicKey}")
    private String publicKey;
    @Value("${pay.zhifubao.apppay.appid}")
    private String appId;
    @Value("${pay.zhifubao.apppay.partnerid}")
    private String partnerId;

    private Logger log = LoggerFactory.getLogger(BindAlipayServiceUtil.class);

    /**
     * 绑定支付宝
     *
     * @param oauth_code
     * @return
     */
    public BindAlipayUserInfo alipayToken(String oauth_code) {
        try {
            AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", appId, privateKey, "json", "utf-8", publicKey, "RSA2");
            AlipaySystemOauthTokenRequest request = new AlipaySystemOauthTokenRequest();
            request.setGrantType("authorization_code");
            request.setCode(oauth_code);
            AlipaySystemOauthTokenResponse response = alipayClient.execute(request);
            if (response.isSuccess()) {
                log.info("绑定支付宝调用成功");
                String accessToken = response.getAccessToken();
                AlipayUserInfoShareResponse info = this.getInfo(accessToken);
                log.info("获取支付宝用户信息：" + info.toString());
                BindAlipayUserInfo userInfo = new BindAlipayUserInfo();
                if (response.isSuccess()) {
                    userInfo.setUserId(info.getUserId());
                    userInfo.setAvatar(info.getAvatar());
                    userInfo.setCity(info.getCity());
                    userInfo.setGender(info.getGender());
                    userInfo.setIsCertified(info.getIsCertified());
                    userInfo.setIsStudentCertified(info.getIsStudentCertified());
                    userInfo.setNickName(info.getNickName());
                    userInfo.setProvince(info.getProvince());
                    userInfo.setUserStatus(info.getUserStatus());
                    userInfo.setUserType(info.getUserType());
                    return userInfo;
                } else {
                    log.error("绑定支付宝调用失败");
                    return null;
                }

            } else {
                return null;
            }
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return null;
    }

    private AlipayUserInfoShareResponse getInfo(String accessToken) throws AlipayApiException {
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", appId, privateKey, "json", "GBK", publicKey, "RSA2");
        AlipayUserInfoShareRequest request = new AlipayUserInfoShareRequest();
        AlipayUserInfoShareResponse response = alipayClient.execute(request, accessToken);
        return response;
    }

    /**
     * 支付宝后台参数拼接
     *
     * @return
     */
    public PersonalCenterAlipayLoginParamVO alipayLoginParam() {

        PersonalCenterAlipayLoginParamVO alipayLoginParamVO = new PersonalCenterAlipayLoginParamVO();

        try {
            SortedMap<String, String> bizModel = new TreeMap<>();
            /****** 参数封装开始 *****/
            bizModel.put("apiname", "com.alipay.account.auth");
            bizModel.put("method", "alipay.open.auth.sdk.code.get");
            bizModel.put("app_id", appId);
            bizModel.put("app_name", "mc");
            bizModel.put("biz_type", "openservice");
            bizModel.put("pid", partnerId);
            bizModel.put("scope", "kuaijie");
            bizModel.put("target_id", IdGenerator.generateId());
            bizModel.put("auth_type", "LOGIN");
            bizModel.put("sign_type", "RSA2");
            bizModel.put("product_id", "APP_FAST_LOGIN");
            String param = AlipaySignature.getSignContent(bizModel);
            String sign = AlipaySignature.rsaSign(param, privateKey, "utf-8", "RSA2");
            log.info("支付宝后台参数拼接 sign：" + sign);
            String signature = param + "&sign=" + URLEncoder.encode(sign, "utf-8");
            log.info("支付宝后台参数拼接 Signature：" + signature);
            alipayLoginParamVO.setSignature(signature);
            return alipayLoginParamVO;
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return alipayLoginParamVO;
    }
}